package com.epam.web_project.bank.command.show_commands;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.epam.web_project.bank.command.Command;
import com.epam.web_project.bank.dao.account_dao.AccountDAO;
import com.epam.web_project.bank.dao.factory.MySQLDAOFactory;
import com.epam.web_project.bank.db.ConnectionPool;
import com.epam.web_project.bank.entity.Account;
import com.epam.web_project.bank.entity.Customer;
import com.epam.web_project.bank.util.AppPropertiesLoader;

public class ShowMainCommand implements Command {
	private Logger logger=Logger.getLogger(ShowMainCommand.class); 
	
	//show main page to an authenticated customer
	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		AppPropertiesLoader propLoader=AppPropertiesLoader.getInstance();
		String resPage;
		HttpSession session = request.getSession();
		Customer customer=(Customer)session.getAttribute("customer");
		if(customer!=null) {
			MySQLDAOFactory daoFactory = new MySQLDAOFactory();
			daoFactory.setConnectionPool(ConnectionPool.getInstance());
			AccountDAO accountDAO = daoFactory.getAccountDAO();
			List<Account> accountsApproved=accountDAO.findByCustomerId(customer.getId(),false);
			List<Account> accountsUnapproved=accountDAO.findByCustomerId(customer.getId(),true);
			if (accountsApproved!=null && !accountsApproved.isEmpty()) {
				request.setAttribute("accountsApproved", accountsApproved);
			}
			if (accountsUnapproved!=null && !accountsUnapproved.isEmpty()) {
				request.setAttribute("accountsUnapproved", accountsUnapproved);
			}
		}
		request.setAttribute("message", session.getAttribute("message"));
		session.removeAttribute("message");
		resPage=propLoader.getProperty("main_page");
		return resPage;
	}

}
